package com.itheima62.mobileguard.engine;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;

import com.itheima62.mobileguard.R;
import com.itheima62.mobileguard.domain.TaskBean;
import com.jaredrummler.android.processes.ProcessManager;
import com.jaredrummler.android.processes.models.AndroidAppProcess;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取所有运行中进程的信息
 * 
 * @author Administrator
 * 
 */
public class TaskManagerEngine {

	/**
	 * 获取系统运行的进程信息
	 *
	 * @param context
	 * @return
	 */
	public static List<TaskBean> getTaskInfos(Context context) {
		// 应用程序管理器
		ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);

		// 应用程序包管理器
		PackageManager pm = context.getPackageManager();

		// 获取正在运行的程序信息, 就是以下粗体的这句代码,获取系统运行的进程，要使用这个方法，需要加载
		//　import com.jaredrummler.android.processes.ProcessManager;
		//　import com.jaredrummler.android.processes.models.AndroidAppProcess;  这两个包, 这两个包附件可以下载
		List<AndroidAppProcess> processInfos = ProcessManager.getRunningAppProcesses();

		List<TaskBean> taskinfos = new ArrayList<TaskBean>();
		// 遍历运行的程序,并且获取其中的信息
		for (AndroidAppProcess processInfo : processInfos) {
			/*if (processInfo.foreground){
				Log.d("taskmanager","taskmanager" + processInfo.name);
			}*/

			TaskBean taskBean = new TaskBean();
			// 应用程序的包名
			String packname = processInfo.name;
			taskBean.setPackName(packname);
			// 湖区应用程序的内存 信息
			android.os.Debug.MemoryInfo[] memoryInfos = am.getProcessMemoryInfo(new int[] { processInfo.pid });
			long memsize = memoryInfos[0].getTotalPrivateDirty() * 1024L;
			taskBean.setMemSize(memsize);
			try {
				// 获取应用程序信息
				ApplicationInfo applicationInfo = pm.getApplicationInfo(packname, 0);
				Drawable icon = applicationInfo.loadIcon(pm);
				taskBean.setIcon(icon);
				String name = applicationInfo.loadLabel(pm).toString();
				taskBean.setName(name);
				if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
					// 用户进程
					taskBean.setSystem(false);
				} else {
					// 系统进程
					taskBean.setSystem(true);
				}
			} catch (NameNotFoundException e) {
				e.printStackTrace();
				// 系统内核进程 没有名称
				taskBean.setName(packname);
				Drawable icon = context.getResources().getDrawable(R.mipmap.ic_launcher);
				taskBean.setIcon(icon);
			}
			if (taskBean != null) {
				taskinfos.add(taskBean);
			}
		}
		return taskinfos;
	}

	/**
	 * @return 所有运行中的进程数据
	 */
	public static List<TaskBean> getAllRunningTaskInfos(Context context) {
		List<TaskBean> datas = new ArrayList<TaskBean>();
		// 获取运行中的进程
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		// 获取包管理器
		PackageManager pm = context.getPackageManager();
		// 获取运行中的进程
	
			List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
			
			for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
				TaskBean bean = new TaskBean();
				// apk的 包名
				String processName = runningAppProcessInfo.processName;// 包名
				// 设置apk的包名
				bean.setPackName(processName);

				// 获取apk的图标和名字

				//有些进程是无名进程
				PackageInfo packageInfo = null;
				try {
					packageInfo = pm.getPackageInfo(processName, 0);
				} catch (NameNotFoundException e) {
					continue;//继续循环 不添加没有名字的进程
					
				}
				//获取apk的图标
				bean.setIcon(packageInfo.applicationInfo.loadIcon(pm));
				//获取apk的名字
				bean.setName(packageInfo.applicationInfo.loadLabel(pm) + "");
				
				if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0){
					//系统apk
					bean.setSystem(true);
				} else {
					bean.setSystem(false);//用户apk 
				}
				
				//获取占用的内存大小
				
				android.os.Debug.MemoryInfo[] processMemoryInfo = am.getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid});
				//获取占用内存 以byte单位
				long totalPrivateDirty = processMemoryInfo[0].getTotalPrivateDirty() * 1024;// 获取运行中占用的内存
				bean.setMemSize(totalPrivateDirty);
	
				datas.add(bean);// 添加一个进程信息
			} // end for
		

		return datas;
	}

	/*private String[] getActivePackages(Context context) {

		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

		final Set<String> activePackages= new HashSet<String>();

		final List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();

		for(ActivityManager.RunningAppProcessInfo processInfo : processInfos) {

			if (processInfo.importance ==ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND

					&& processInfo.processState == ActivityManager.START_TASK_TO_FRONT){

				activePackages.addAll(Arrays.asList(processInfo.pkgList));

				Log.d(TAG,"====processInfo.processState " + processInfo.processState + processInfo.processName);

			}

		}

		return activePackages.toArray(new String[activePackages.size()]);

	}*/

	/*static class RecentUseComparator implements Comparator<UsageStats>

	{

		@Override
		public int compare(UsageStats lhs,UsageStats rhs) {

			return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed()) ? -1 : (lhs.getLastTimeUsed()== rhs.getLastTimeUsed()) ? 0 : 1;
		}

	}



	private StringgetTopPackage(Context context) {

		long ts = System.currentTimeMillis();

		RecentUseComparator mRecentComp = new RecentUseComparator();

		UsageStatsManager mUsageStatsManager =(UsageStatsManager) context.getSystemService("usagestats");
		//查询ts-10000 到ts这段时间内的UsageStats，由于要设定时间限制，所以有可能获取不到
		List<UsageStats> usageStats =mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,ts - 10000, ts);

		if (usageStats == null) return "";
		if (usageStats.size() == 0) return "";
		Collections.sort(usageStats,mRecentComp);
		Log.d(TAG,"====usageStats.get(0).getPackageName()"+ usageStats.get(0).getPackageName());
		return usageStats.get(0).getPackageName();
	}*/

	/**
	 * @return 获取可用内存的大小
	 */
	public static long getAvailMemSize(Context context) {
		long size = 0;
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		MemoryInfo outInfo = new MemoryInfo();
		// MemoryInfo 存放内存的信息
		am.getMemoryInfo(outInfo);

		// 把kb 转换成byte
		size = outInfo.availMem;

		return size;
	}

	/**
	 * @return 总内存大小
	 */
	public static long getTotalMemSize(Context context) {
		long size = 0;

		/*
		 * //Activity管理器,获取运行相关信息 ActivityManager am = (ActivityManager)
		 * context.getSystemService(Context.ACTIVITY_SERVICE);
		 * 
		 * MemoryInfo outInfo = new MemoryInfo(); //MemoryInfo 存放内存的信息
		 * am.getMemoryInfo(outInfo ); //获取总内存大小，16级别以上 ,读取内存文件 size =
		 * outInfo.totalMem;
		 */

		// 读取配置文件来获取总内存大小

		File file = new File("/proc/meminfo");
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file)));
			// //zip流 pipe流

			String totalMemInfo = reader.readLine();

			int startIndex = totalMemInfo.indexOf(':');
			int endIndex = totalMemInfo.indexOf('k');
			// 单位是kb
			totalMemInfo = totalMemInfo.substring(startIndex + 1, endIndex)
					.trim();
			size = Long.parseLong(totalMemInfo);
			size *= 1024;// byte单位
		} catch (Exception e) {
			e.printStackTrace();
		}

		return size;
	}
}
